﻿
using AuroraPlatform.TCP;
using AuroraPlatform.Tools;
using AuroraPlatform.View;
using AuroraPlatform.View.Level3;
using AuroraPlatform.View.UserManager;
using AuroraPlatform.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace AuroraPlatform
{
    public partial class MainPage : UserControl
    {
        public const string PortalUri = "/View/LightingNavigation.xaml";
        public const string Level2Uri = "/View/Level2/LightingClassView.xaml";
        public const string Level3Uri = "/View/Level3/LightingListView.xaml";
        public const string Level4Uri = "/View/Level4/LightingVersionView.xaml";
        public const string Level5Uri = "/View/Level5/LightingView.xaml";

        private ResItem _emptyItem;
        private ResItem EmptyItem
        {
            get
            {
                if (_emptyItem == null)
                {
                    ResItem.Builder builder = new ResItem.Builder();
                    builder.SetItemName("全部");
                    _emptyItem = builder.Build();
                }  
                return _emptyItem;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            Navigation.Navigated += Navigation_Navigated;
            AddBtn.Click += AddBtn_Click;
            BackLink.Click += BackLink_Click;
            NextLink.Click += NextLink_Click;
            EditBtn.Click += EditBtn_Click;
            ClearBtn.Click += ClearBtn_Click;
            SearchBtn.Click += SearchBtn_Click;
            UserBtn.Click += UserBtn_Click;
            DeleteBtn.Click += DeleteBtn_Click;
            ExportExcelBtn.Click += ExportExcelBtn_Click;
            ExportPdfBtn.Click += ExportPdfBtn_Click;
            ViewBtn.Click += ViewBtn_Click;
            CartBtn.Click += CartBtn_Click;
            this.DataContext = BusinessContext.Singleton;

            BusinessContext.Singleton.ParamIterator.GoNew(
            new NaviToPortalParam
            {
                CurrentUrl = MainPage.PortalUri,
                //SourceUrl = MainPage.PortalUri
            });
            Navigation.Navigate(new Uri(PortalUri, UriKind.RelativeOrAbsolute));
            GetStaticResource();
            AutoLogin();
        }

        private void CartBtn_Click(object sender, RoutedEventArgs e)
        {
            if (BusinessContext.Singleton.Items.Count == 0)
            {
                MessageHelper.ShowMessage("请添加打印的灯具信息。");
                return;
            }

            CartWindow window = new CartWindow();
            window.Show();
        }

        private async void AutoLogin()
        {
            try
            {
                IsolatedStorageSettings appSetting = IsolatedStorageSettings.ApplicationSettings;
                if (appSetting.Contains("user"))
                {
                    string value = appSetting["user"].ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        string[] array = value.Split(',');
                        if (array[2] == "1")
                        {
                            if (array[3] == "1")
                                return;

                            WebServiceProxy proxy = new WebServiceProxy();
                            busy.IsBusy = true;
                            busy.BusyContent = "正在登陆，请稍等......";
                            User user = await proxy.Login(array[0], array[1]);
                            busy.IsBusy = false;
                            if (user != null)
                            {
                                BusinessContext.Singleton.User = user;
                                GetLabels();
                                BusinessContext.Singleton.TargetPage = BusinessContext.Singleton.TargetPage;
                            }
                            else
                            {
                                MessageHelper.ShowWarning("用户名或密码错误。");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
 
        }

        private void ViewBtn_Click(object sender, RoutedEventArgs e)
        {
            if(BusinessContext.Singleton.TargetPage == PageLevel.Fourth)
            {
                NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
                if (parameter != null && parameter is NaviTo4Param)
                {
                    NaviTo4Param param = (NaviTo4Param)parameter;
                    BusinessContext.Singleton.ParamIterator.GoNew(
                        new NaviTo5ViewParam() 
                        { 
                            ID = param.ID,
                            CurrentUrl = MainPage.Level5Uri
                            //SourceUrl = MainPage.Level4Uri
                        });
                    Navigation.Navigate(new Uri(Level5Uri, UriKind.RelativeOrAbsolute));
                }
            }
        }

        private IList<ResItem> InsertEmptyItem(IEnumerable<ResItem> items)
        {
            List<ResItem> list = new List<ResItem>();
            list.AddRange(items);
            list.Insert(0, EmptyItem);
            return list;
        }

        private async void GetStaticResource()
        {
            WebServiceProxy proxy = new WebServiceProxy();
            ResArray resArray = await proxy.GetStaticResource();

            ResourceProvider.ResItems.Clear();
            ResourceProvider.ResItems.AddRange(resArray.ResList);

            ResourceProvider resPovider = new ResourceProvider();
            UseArea.ItemsSource = InsertEmptyItem(resPovider.UseArea);
            ProdType.ItemsSource = InsertEmptyItem(resPovider.ProdTypes);
            LightingType.ItemsSource = InsertEmptyItem(resPovider.LightingType);
            SetupType.ItemsSource = InsertEmptyItem(resPovider.SetupType);
        }

        private async void GetLabels()
        {
            WebServiceProxy proxy = new WebServiceProxy();
            SignLabelArray names = await proxy.SearchProdName();
            if (names == null)
                return;

            List<SignModel> list = new List<SignModel>();
            foreach (SignLabel label in names.SignLabelList)
            {
                list.Add(new SignModel() { Name = label.Name, IsMain = label.IsMain });
            }


            list.Insert(0, new SignModel() { Name = "全部", IsMain = -1 });
            ProductLable.ItemsSource = list;
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            if (BusinessContext.Singleton.User == null)
            {
                LoginWindow window = new LoginWindow();
                window.Closed += (sender1, e1) =>
                {
                    if (window.DialogResult.HasValue && window.DialogResult.Value)
                    {
                        GetLabels();
                        BusinessContext.Singleton.TargetPage = BusinessContext.Singleton.TargetPage;

                        try
                        {
                            IsolatedStorageSettings appSetting = IsolatedStorageSettings.ApplicationSettings;

                            StringBuilder sb = new StringBuilder();
                            sb.AppendFormat(
                                "{0},{1},{2},{3}", 
                                BusinessContext.Singleton.User.Name,
                                BusinessContext.Singleton.User.Password,
                                window.AutoLogin.IsChecked == true ? "1" : "0",
                                "0");
                            appSetting["user"] = sb.ToString();
                            appSetting.Save();
                        }
                        catch
                        {

                        }
                    }
                };
                window.Show();
            }
            else
            {

                try
                {
                    IsolatedStorageSettings appSetting = IsolatedStorageSettings.ApplicationSettings;
                    if (appSetting.Contains("user"))
                    {
                        string value = appSetting["user"].ToString();
                        if (!string.IsNullOrEmpty(value))
                        {
                            string[] array = value.Split(',');
                            if (array[2] == "1")
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendFormat("{0},{1},{2},{3}", array[0],  array[1], array[2], "1");
                                appSetting["user"] = sb.ToString();
                                appSetting.Save();
                            }
                        }
                    }
                }
                catch
                {
                }

                HtmlPage.Window.Navigate(HtmlPage.Document.DocumentUri);
            }
        }

        private void UserBtn_Click(object sender, RoutedEventArgs e)
        {
            UserListWindow window = new UserListWindow();
            window.Show();
        }

        private void ExportPdfBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Navigation.Content is IExportData)
            {
                IExportData page = (IExportData)Navigation.Content;
                page.ExportToPdf();
            }
        }

        private void ExportExcelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Navigation.Content is IExportData)
            {
                IExportData page = (IExportData)Navigation.Content;
                page.ExportToExcel();
            }
        }

        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            BusinessContext.Singleton.ParamIterator.GoNew(
                new NaviTo5NewParam()
                {
                    CurrentUrl = MainPage.Level5Uri
                    //SourceUrl = uri
                });
            Navigation.Navigate(new Uri(Level5Uri, UriKind.RelativeOrAbsolute));
        }

        private async void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (BusinessContext.Singleton.TargetPage == PageLevel.Fourth)
            {
                NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
                if (parameter != null && parameter is NaviTo4Param)
                {
                    NaviTo4Param param = (NaviTo4Param)parameter;
                    WebServiceProxy proxy = new WebServiceProxy();
                    bool result = await proxy.DeleteProd(param.ID);
                    if (result)
                    {
                        MessageHelper.ShowMessage("删除灯具成功。");
                        if (Navigation.CanGoBack)
                            Navigation.GoBack();
                    }
                    else
                    {
                        MessageHelper.ShowError("删除灯具失败。");
                    }
                }
            }
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            if (BusinessContext.Singleton.TargetPage == PageLevel.Fourth)
            {
                NaviToParam parameter = BusinessContext.Singleton.ParamIterator.Current;
                if (parameter != null && parameter is NaviTo4Param)
                {
                    NaviTo4Param param = (NaviTo4Param)parameter;
                    BusinessContext.Singleton.ParamIterator.GoNew(
                        new NaviTo5EditParam() 
                        { 
                            ID = param.ID,
                            CurrentUrl = MainPage.Level5Uri
                            //SourceUrl = MainPage.Level4Uri
                        });
                    Navigation.Navigate(new Uri(Level5Uri, UriKind.RelativeOrAbsolute));
                }
            }
        }

        private void BackLink_Click(object sender, RoutedEventArgs e)
        {
            BusinessContext.Singleton.ParamIterator.GoBack();
            NaviToParam param = BusinessContext.Singleton.ParamIterator.Current;
            if (param != null)
                Navigation.Navigate(new Uri(param.CurrentUrl, UriKind.RelativeOrAbsolute));
        }

        private void NextLink_Click(object sender, RoutedEventArgs e)
        {
            BusinessContext.Singleton.ParamIterator.GoForward();
            NaviToParam param = BusinessContext.Singleton.ParamIterator.Current;
            if (param != null)
                Navigation.Navigate(new Uri(param.CurrentUrl, UriKind.RelativeOrAbsolute));
        }

        private void Navigation_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            BackLink.IsEnabled = false;
            NextLink.IsEnabled = false;

            if(BusinessContext.Singleton.ParamIterator.CanGoBack)
                BackLink.IsEnabled = true;

            if (BusinessContext.Singleton.ParamIterator.CanGoForward)
                NextLink.IsEnabled = true;

            if (e.Content is IPageProvider)
            {
                IPageProvider provider = e.Content as IPageProvider;
                provider.Navigation = Navigation;
                BusinessContext.Singleton.TargetPage = provider.PageLevel;
            }
        }

        private void OnLinkMouseEnter(object sender, MouseEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            link.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 51, 51));
        }

        private void OnLinkMouseLeave(object sender, MouseEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;
            link.Foreground = new SolidColorBrush(Color.FromArgb(255, 51, 102, 204));
        }

        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            if (LSPowerStart.Value > 0 && LSPowerEnd.Value > 0)
            {
                if (LSPowerStart.Value > LSPowerEnd.Value)
                {
                    MessageHelper.ShowMessage("参与搜索的最小光源功率不能大于最大光源功率。");
                    return;
                }
            }

            if (MarketPriceStart.Value > 0 && MarketPriceEnd.Value > 0)
            {
                if (MarketPriceStart.Value > MarketPriceEnd.Value)
                {
                    MessageHelper.ShowMessage("参与搜索的最小市场价格不能大于最大市场价格。");
                    return;
                }
            }

            BusinessContext.Singleton.ParamIterator.GoNew(
                new SearchNaviToParam() 
                {
                    Parameter = GetCondProdList(),
                    CurrentUrl = MainPage.Level3Uri
                });
            if(Navigation.Content is LightingListView)
            {
                LightingListView listView = (LightingListView)Navigation.Content;
                listView.Loading();
            }
            else
            {
                Navigation.Navigate(new Uri(Level3Uri, UriKind.RelativeOrAbsolute));
            }
        }

        private async void Import_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "灯具包 (*.zip;*.rar)|*.zip;*.rar";
            bool? result = fileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                byte[] bytes = null;
                using (Stream stream = fileDialog.File.OpenRead())
                {
                    bytes = Utility.ReadFully(stream);
                }

                try
                {
                    busy.IsBusy = true;
                    busy.BusyContent = "正在导入数据，请稍等......";
                    SetTimer();
                    await TCPClient.Current.ConnectAsync();
                    byte[] response = await TCPClient.Current.Call(1, bytes);
                    busy.IsBusy = false;
                    MessageHelper.ShowMessage(response != null && response.Length > 0 && response[0] == (byte)1 ? "导入成功。" : "导入失败。");
                }
                catch (Exception ex)
                {
                    MessageHelper.ShowMessage("导入失败：" + ex.StackTrace + ex.Message);
                    busy.IsBusy = false;
                }
            }
        }

        private void SetTimer()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMinutes(20);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            DispatcherTimer timer = (DispatcherTimer)sender;
            timer.Stop();
            if (busy.IsBusy)
            {
                busy.IsBusy = false;
                MessageHelper.ShowError("服务器响应超时，请重新操作。");
                return;
            }
        }

        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ProductName.Text))
                ProductName.Text = string.Empty;

            if(UseArea.SelectedIndex > 0)
                UseArea.SelectedIndex = 0;

            if (ProdType.SelectedIndex > 0)
                ProdType.SelectedIndex = 0;

            if (!string.IsNullOrEmpty(ProductVersion.Text))
                ProductVersion.Text = string.Empty;

            if (ProductLable.SelectedIndex > 0)
                ProductLable.SelectedIndex = 0;

            if (LightingType.SelectedIndex > 0)
                LightingType.SelectedIndex = 0;

            if (LSPowerStart.Value > 0)
                LSPowerStart.Value = 0;

            if (LSPowerEnd.Value > 0)
                LSPowerEnd.Value = 0;

            if (LSTemperature.SelectedIndex > 0)
                LSTemperature.SelectedIndex = 0;

            if (LSCRI.SelectedIndex > 0)
                LSCRI.SelectedIndex = 0;

            if (Angle.SelectedIndex > 0)
                Angle.SelectedIndex = 0;

            if (SetupType.SelectedIndex > 0)
                SetupType.SelectedIndex = 0;

            if (MarketPriceStart.Value > 0)
                MarketPriceStart.Value = 0;

            if (MarketPriceEnd.Value > 0)
                MarketPriceEnd.Value = 0;
        }

        private CondPordList GetCondProdList()
        {
            CondPordList.Builder builder = new CondPordList.Builder();
            if (!string.IsNullOrEmpty(ProductName.Text))
                builder.SetSeries(ProductName.Text);

            if (UseArea.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)UseArea.SelectedItem;
                builder.SetUsePlace(resItem.ItemID);
            }

            if (ProdType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)ProdType.SelectedItem;
                builder.SetProductClass(resItem.ItemID);
            }

            if (!string.IsNullOrEmpty(ProductVersion.Text))
                builder.SetProductVersion(ProductVersion.Text);

            if (ProductLable.SelectedIndex > 0)
            {
                SignModel resItem = (SignModel)ProductLable.SelectedItem;
                builder.SetProductLable(resItem.Name);
            }

            if (LightingType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)LightingType.SelectedItem;
                builder.SetLightingSourceClass(resItem.ItemID);
            }

            if (LSPowerStart.Value > 0)
                builder.SetStartLightingPower((int)LSPowerStart.Value);

            if (LSPowerEnd.Value > 0)
                builder.SetEndLightingPower((int)LSPowerEnd.Value);

            if (LSTemperature.SelectedIndex > 0)
                builder.SetColor(LSTemperature.SelectedIndex);

            if (LSCRI.SelectedIndex > 0)
                builder.SetCri(LSCRI.SelectedIndex);

            if (Angle.SelectedIndex > 0)
                builder.SetAngle(Angle.SelectedIndex);

            if (SetupType.SelectedIndex > 0)
            {
                ResItem resItem = (ResItem)SetupType.SelectedItem;
                builder.SetSetup(resItem.ItemID);
            }

            if (MarketPriceStart.Value > 0)
                builder.SetStartMarketPrice((int)MarketPriceStart.Value);

            if (MarketPriceEnd.Value > 0)
                builder.SetEndMarketPrice((int)MarketPriceEnd.Value);

#if DEBUG
            LogWindow.AddLog("搜索参数：" + builder.Build().ToString());
#endif

            return builder.Build();
        }

        private bool _deletedStatus = false;
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            dropDown.IsOpen = false;
            if (ListBox.SelectedIndex == 0)
            {
                if (_deletedStatus)
                    return;

                _deletedStatus = true;
                LightingListView ls = (LightingListView)Navigation.Content;
                ls.ShowChecked();
            }
            else
            {
                if (!_deletedStatus)
                    return;

                LightingListView ls = (LightingListView)Navigation.Content;
                if (ListBox.SelectedIndex == 1)
                {
                    _deletedStatus = false;
                    ls.ShowUnChecked();
                }
                else if(ListBox.SelectedIndex == 2)
                {
                    ls.SetAllChecked();
                }
                else if (ListBox.SelectedIndex == 3)
                {
                    ls.ClearChecked();
                }
                else if (ListBox.SelectedIndex == 4)
                {
                    ls.BatchDeleted();
                }
            }
        }

        private void ChangeMainClicked(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            SignModel model = (SignModel)btn.DataContext;
            
            WebServiceProxy proxy = new WebServiceProxy();
            proxy.SignLable(model.Name);
            model.IsMain = 1;
        }

        private void ChangeNormalClicked(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            SignModel model = (SignModel)btn.DataContext;

            WebServiceProxy proxy = new WebServiceProxy();
            proxy.UnSignLable(model.Name);
            model.IsMain = 0;
        }

        private void Viewbox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BusinessContext.Singleton.ParamIterator.GoNew(
                new NaviToPortalParam()
                {
                    CurrentUrl = PortalUri
                });
            Navigation.Navigate(new Uri(PortalUri, UriKind.RelativeOrAbsolute));
        }
    }
}
